import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2024-11-13
 * Time: 21:23
 */
public class Test {
    private static int count = 0;
    public static void main(String[] args) {
        // 创建线程池
        ExecutorService service = Executors.newFixedThreadPool(2);
        // 使用线程池来模拟生产者-消费者模型
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(10);
        // 生产者
        Thread producer = new Thread(()->{
            while (true) {
                // 源源不断地在生产任务
                try {
                    // 先 生产任务
                    System.out.println("生产者生产任务"+(++count)+"...");
                    Runnable task = () -> {};
                    Thread.sleep(1000);
                    queue.put(task);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        // 消费者
        Thread consumer = new Thread(()->{
            while (true) {
                // 源源不断地去消费任务
                try {
                    // 再 消费任务
                    Thread.sleep(1000);
                    service.submit(queue.take());
                    System.out.println("消费者消费任务...");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        producer.start();
        consumer.start();
    }
}
